﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using DAL.Entity;
using DAL.Persistencia;

namespace NewTierra.Pages
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.AddHeader("Last-Modified", DateTime.Now.ToString());
            Response.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
            Response.AddHeader("Pragma", "no-cache");
        }

        protected void AutenticarUsuario(object sender, AuthenticateEventArgs e)
        {
            try
            {
                string Email = formLogin.UserName;

                string Senha = FormsAuthentication.HashPasswordForStoringInConfigFile
                                                        (formLogin.Password, "MD5");

                UsuarioDAL d = new UsuarioDAL();

                Usuario u = d.ObterUsuario(Email, Senha);

                if (u != null)
                {
                    Session.Add("userLogado", u);

                    Session.Add(Email, u);
                    Session["emailLogado"] = Email;

                    //Dictionary<string, object> userLogado = new Dictionary<string, object>();
                    //userLogado.Add(Email, u);
                    //Session["userLogado"] = userLogado;
                    WriteCookies();

                    e.Authenticated = true;
                }
                else
                {
                    e.Authenticated = false;
                }
            }
            catch (Exception ex)
            {
                formLogin.FailureText = ex.Message;
            }

        }

        private void WriteCookies()
        {
            HttpCookie myCookie = new HttpCookie("UsuarioNewTierra");
            Usuario u = Session["userLogado"] as Usuario;
            myCookie["id"] = u.US_id.ToString();
            myCookie.Expires = DateTime.Now.AddMinutes(30);
            Response.Cookies.Add(myCookie);         
        }

    }
}